package org.devio.takephoto.app;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;

import com.ankiang.treeprint.R;
import com.ankiang.treeprint.base.BaseFragment;
import com.ankiang.treeprint.fragment.components.TRAddItemFragment;
import com.ankiang.treeprint.fragment.components.TRViewImageFragment;
import com.ankiang.treeprint.model.LOG;
import com.ankiang.treeprint.model.TRGroupItem;
import com.ankiang.treeprint.model.TRItemNode;
import com.ankiang.treeprint.view.TRConfig;

import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.TakePhotoOptions;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 继承这个类来让Fragment获取拍照的能力<br>
 * Author: crazycodeboy
 * Date: 2016/9/21 0007 20:10
 * Version:3.0.0
 * 技术博文：http://www.devio.org
 * GitHub:https://github.com/crazycodeboy
 * Email:crazycodeboy@gmail.com
 */
public class TakePhotoFragment extends BaseFragment implements TakePhoto.TakeResultListener, InvokeListener {
    private static final String TAG = TakePhotoFragment.class.getName();
    public static final int OP_CHOOSE_GROUP_IMAGE = 1;
    public static final int OP_CHOOSE_ITEM_IMAGE = 2;

    int mOp = OP_CHOOSE_ITEM_IMAGE;

    private InvokeParam invokeParam;
    private TakePhoto takePhoto;


    @BindView(R.id.chooseLocalButton)
    Button chooseLocalButton;
    @BindView(R.id.camaraButton)
    Button camaraButton;

    @BindView(R.id.cancelButton)
    Button cancelButton;

    @BindView(R.id.clearButton)
    Button clearButton;


    @BindView(R.id.viewLargeImageButton)
    Button viewLargeImageButton;

    private ImageButton imageButton;

//    private Drawable imageDrawable;
    // 配置
    private TRConfig conf;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

//    public void setImageDrawable(Drawable x) {
//        this.imageDrawable = x;
//    }

    @Override
    protected View onCreateView() {

        FrameLayout layout = (FrameLayout) LayoutInflater.from(getActivity()).inflate(R.layout.tr_fragment_image_chooser, null);
        ButterKnife.bind(this, layout);

        conf = TRConfig.getInstance();

        initListener();
        return layout;
    }

    private void initListener() {
        viewLargeImageButton.setOnClickListener(v -> {
            TRViewImageFragment fragment = new TRViewImageFragment();
            fragment.setDrawable(this.imageButton.getDrawable());
            startFragment(fragment);

        });

        chooseLocalButton.setOnClickListener(v -> onClick(v));
        cancelButton.setOnClickListener(v -> popBackStack());
        clearButton.setOnClickListener(v -> {
            Bundle bundle = getArguments();
            if (bundle != null) {
                if (mOp == OP_CHOOSE_ITEM_IMAGE) {
                    TRItemNode item = (TRItemNode) bundle.getSerializable(TRAddItemFragment.KEY_DATA);
                    if (item != null) {
                        item.setImage("");
                        int imgId = conf.getImgId(item.getSex());
                        imageButton.setImageResource(imgId);
                        popBackStack();
                    }
                } else if (mOp == OP_CHOOSE_GROUP_IMAGE) {
                    TRGroupItem item = (TRGroupItem) bundle.getSerializable(TRAddItemFragment.KEY_DATA);
                    if (item != null) {
                        item.setImage("");
                        int imgId = R.drawable.group_image;
                        imageButton.setImageResource(imgId);
                        popBackStack();
                    }
                }
            }

        });

        camaraButton.setOnClickListener(v -> {

            int limit = 1;
            File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Uri imageUri = Uri.fromFile(file);

            configCompress(takePhoto);
            configTakePhotoOption(takePhoto);

            takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
        });
    }


    public void onClick(View view) {
        TakePhoto takePhoto = getTakePhoto();


        int limit = 1;
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri = Uri.fromFile(file);

        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);

        takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());


    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(true);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    private void configCompress(TakePhoto takePhoto) {

        int maxSize = 1024;
        int width = 1024;
        int height = 1024;
        boolean showProgressBar = true;
        boolean enableRawFile = true;
        CompressConfig config;
//        if (rgCompressTool.getCheckedRadioButtonId() == R.id.rbCompressWithOwn) {
        config = new CompressConfig.Builder().setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
//        } else {
//            LubanOptions option = new LubanOptions.Builder().setMaxHeight(height).setMaxWidth(width).setMaxSize(maxSize).create();
//            config = CompressConfig.ofLuban(option);
//            config.enableReserveRaw(enableRawFile);
//        }
        takePhoto.onEnableCompress(config, showProgressBar);


    }


    private CropOptions getCropOptions() {

        int height = 128;//Integer.parseInt(etCropHeight.getText().toString());
        int width = 128;//Integer.parseInt(etCropWidth.getText().toString());
        boolean withWonCrop = true;

        CropOptions.Builder builder = new CropOptions.Builder();

//        if (rgCropSize.getCheckedRadioButtonId() == R.id.rbAspect) {
        builder.setAspectX(width).setAspectY(height);
//        } else {
//            builder.setOutputX(width).setOutputY(height);
//        }
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

//        Log.d("onActivityResult", "data ");

        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        Log.i(TAG, "takeSuccess：" + result.getImage().getCompressPath());
        if (imageButton != null) {
            String imgFilePath = result.getImage().getCompressPath();

            FileInputStream fis;
            try {
                fis = new FileInputStream(new File(imgFilePath));//文件输入流
                if (fis != null) {
                    Bitmap bmp = BitmapFactory.decodeStream(fis);
                    imageButton.setImageBitmap(bmp);

                    Bundle bundle = getArguments();
                    if (bundle != null) {
                        if (mOp == OP_CHOOSE_ITEM_IMAGE) {
                            TRItemNode item = (TRItemNode) bundle.getSerializable(TRAddItemFragment.KEY_DATA);
                            if (item != null) {
                                item.setImage(imgFilePath);
                            }
                        } else if (mOp == OP_CHOOSE_GROUP_IMAGE) {
                            TRGroupItem item = (TRGroupItem) bundle.getSerializable(TRAddItemFragment.KEY_DATA);
                            if (item != null) {
                                item.setImage(imgFilePath);

                                Drawable imgDrawable = null;
                                String imgPath = item.getImage();

                                if (null != imgPath && !imgPath.equals("")) {
                                    imgDrawable = Drawable.createFromPath(imgPath);
                                }
                                if (imgDrawable == null) { // 如果上一部没有创建成功，也会调用这里
                                    imgDrawable = getResources().getDrawable(R.drawable.group_image);
                                }


                                imageButton.setImageDrawable(imgDrawable);
                            }
                        }
                    }
                    popBackStack();
                } else {
                    Toast.makeText(getContext(), "读取文件失败！！", Toast.LENGTH_SHORT).show();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                LOG.jLoge("文件未找到: ", e.getMessage());
                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

        }

    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    public void setImageButton(ImageButton imageButton) {
        this.imageButton = imageButton;
    }

    public void setOp(int mOp) {
        this.mOp = mOp;
    }
}
